package com.darker.yygh.user.service.impl;

import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.darker.yygh.exception.YyghException;
import com.darker.yygh.helper.JwtHelper;
import com.darker.yygh.result.ResultCodeEnum;
import com.darker.yygh.user.mapper.UserInfoMapper;
import com.darker.yygh.user.service.PatientApiService;
import com.darker.yygh.user.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Autowired
    PatientApiService patientApiService;


    //认证审批
    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus == 2 || authStatus == -1) {//2通过 -1不通过
            LambdaUpdateWrapper<UserInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(UserInfo::getId, userId)
                    .set(UserInfo::getAuthStatus, authStatus);
            this.update(updateWrapper);
        }

    }

    //用户详情信息
    @Override
    public Map<String, Object> show(Long userId) {
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        Map<String, Object> param = new HashMap<>();
        param.put("userInfo", userInfo);
        //根据userid查询就诊人信息
        List<Patient> patientList = patientApiService.findAllByUserId(userId);
        param.put("patientList", patientList);

        return param;
    }

    //锁定用户状态
    @Override
    public void lock(Long userId, Integer status) {

        LambdaUpdateWrapper<UserInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserInfo::getId, userId)
                .set(UserInfo::getStatus, status);
        this.update(updateWrapper);
    }

    //用户列表（条件查询带分页)
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParm, UserInfoQueryVo userInfoQueryVo) {

        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        //对条件值进行非空判断
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(name), UserInfo::getName, name)
                .eq(!StringUtils.isEmpty(status), UserInfo::getStatus, status)
                .eq(!StringUtils.isEmpty(authStatus), UserInfo::getAuthStatus, authStatus)
                .ge(!StringUtils.isEmpty(createTimeBegin), UserInfo::getCreateTime, createTimeBegin)    //大于createTimeBegin
                .le(!StringUtils.isEmpty(createTimeEnd), UserInfo::getCreateTime, createTimeEnd);   //小于createTimeEnd

        //调用baseMapper 分页查询
        IPage<UserInfo> userInfoPage = baseMapper.selectPage(pageParm, queryWrapper);
        List<UserInfo> userInfoList = userInfoPage.getRecords();
        userInfoList.stream().forEach(item -> {
            this.packageUserInfo(item);
        });


        return userInfoPage;
    }

    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;
    }

    //用户认证 根据用户Id插入认证的相应数据
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        BeanUtils.copyProperties(userAuthVo, userInfo);
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        baseMapper.updateById(userInfo);
    }

    //根据openid查询
    @Override
    public UserInfo selectWxInfoOpenId(String openid) {

        UserInfo userInfo = baseMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getOpenid, openid));

        return userInfo;
    }

    //用户手机号登录接口
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //从loginVo获取输入的手机号和验证码
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        //如果手机号或者验证码为空抛出异常
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        //从redis缓存中通过手机号获取验证码
        String redisCode = redisTemplate.opsForValue().get(phone);
        //如果验证码不一致 抛出异常
        if (!redisCode.equals(code)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //绑定手机号码
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.selectWxInfoOpenId(loginVo.getOpenid());
            if (null != userInfo) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        if (userInfo == null) {
            //判断手机号是否第一次登录:根据手机号查询数据库 如果不存在则是第一次登录
            LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserInfo::getPhone, phone);
            userInfo = baseMapper.selectOne(lambdaQueryWrapper);
            if (userInfo == null) {//第一次使用手机号登录
                //添加信息到数据库
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
        }
        //检验是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }


        //登录成功封装用户名 token信息
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {//如果名称为空返回昵称
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name))//如果赋值昵称后名称还为空则返回手机号
        {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);

        return map;
    }
}
